<template>
  <div class="app-container">
    <div class="action-container">
      <el-button @click="handleCreateFilingEvent">增加<i class="el-icon--right" /></el-button>
      <el-button type="primary" @click.prevent="handleImportFilingEvent()">导入<i class="el-icon--right" /></el-button>
      <el-button @click.prevent="downloadTemplate()">下载模板<i class="el-icon--right"></i></el-button>
    </div>
    <div class="filter-container">
      <el-input v-model="listQuery.f_lk_serial" style="width: 200px;" class="filter-item" placeholder="案件编码" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.f_lk_involvedPerson" style="width: 200px; margin-left: 10px;" class="filter-item" placeholder="涉案人员" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.f_eq_parentOrgId" style="width: 150px; margin-left: 10px;" class="filter-item" placeholder="一级机关" @change='onOrgList1Changed'>
        <el-option label="全部(一级机关）" value="" />
        <el-option v-for="item in orgList1" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-select v-model="listQuery.f_eq_orgId" style="width: 150px; margin-left: 10px;" class="filter-item" placeholder="二级机关" @change="handleFilter">
        <el-option label="全部(二级机关）" value="" />
        <el-option v-for="item in orgList2" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-select v-model="listQuery.f_eq_status" style="width: 120px; margin-left: 10px;" class="filter-item" placeholder="状态" @change="handleFilter">
        <el-option label="全部" value="" />
        <el-option label="未处理" value="0" />
        <el-option label="已移交" value="1" />
        <el-option label="已审结" value="2" />
        <el-option label="已结案" value="3" />
      </el-select>
      <el-button class="filter-item" type="success" icon="el-icon-search" @click="resetFiler">重置</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <el-table v-loading.body="listLoading" :data="list" element-loading-text="数据正在加载中，请稍后..." border fit highlight-current-row>
      <el-table-column align="center" label="ID" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <!--
      <el-table-column label="线索编码">
        <template slot-scope="scope">
          {{ (scope.row.clue || {}).serial }}
        </template>
      </el-table-column>
      <el-table-column label="被调查人">
        <template slot-scope="scope">
          {{ scope.row.respondent }}
        </template>
      </el-table-column>
      -->
      <el-table-column label="案件编码">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleShowWorkflowDialogEvent(scope.row)">{{ scope.row.serial }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="涉案人员编码">
        <template slot-scope="scope">
          {{ scope.row.involvedPerson }}
        </template>
      </el-table-column>
      <el-table-column label="立案时间">
        <template slot-scope="scope">
          {{ scope.row.filingTime }}
        </template>
      </el-table-column>
      <el-table-column label="纪委立案机关" width="210">
        <template slot-scope="scope">
          {{ (scope.row.disciplinaryOrg || {}).name }}
        </template>
      </el-table-column>
      <el-table-column label="监委立案机关" width="210">
        <template slot-scope="scope">
          {{ (scope.row.supervisoryOrg || {}).name }}
        </template>
      </el-table-column>
      <el-table-column label="移送审理时间">
        <template slot-scope="scope">
          {{ scope.row.transferTime }}
        </template>
      </el-table-column>
      <el-table-column label="审理机关" width="210">
        <template slot-scope="scope">
          {{ (scope.row.trialOrg || {}).name }}
        </template>
      </el-table-column>
      <el-table-column label="审结时间">
        <template slot-scope="scope">
          {{ scope.row.concludeTime }}
        </template>
      </el-table-column>
      <el-table-column label="结案时间">
        <template slot-scope="scope">
          {{ scope.row.closureTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusClassFilter">{{ scope.row.status | statusValueFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="210">
        <template slot-scope="scope">
          <el-button type="" size="small" @click="handleUpdateFilingEvent(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="handleDeleteFilingEvent(scope.row.id)">删除</el-button>
          <el-button type="primary" size="small" @click.prevent="handleExportExcelEvent(scope.row.id)">导出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination
        background
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30,50]"
        :page-size="listQuery.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="filing" label-position="left" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item label="ID" prop="id">
          <span>{{ filing.id }}</span>
        </el-form-item>
        <el-form-item label="线索编码" prop="clueId">
          <el-select v-model="filing.clueId" placeholder="线索编码">
            <el-option label="请选择" :value="0" />
            <el-option v-for="item in clueList" :key="item.id" :label="item.serial + '(' + item.respondent + ')'" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="被调查人" prop="respondent">
          <el-input v-model="filing.respondent" />
        </el-form-item>
        <el-form-item label="案件编码" prop="serial">
          <el-input v-model="filing.serial" />
        </el-form-item>
        <el-form-item label="涉案人员编码" prop="involvedPerson">
          <el-input v-model="filing.involvedPerson" />
        </el-form-item>
        <el-form-item label="纪委立案机关" prop="disciplinaryOrgId">
          <div class="el-form-item__content">
            <el-select v-model="disciplinaryParentId" @change='onDisciplinaryParentIdChanged' placeholder="先选择一级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in orgList1" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="filing.disciplinaryOrgId" placeholder="再选择二级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in disciplinaryOrgList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="监委立案机关" prop="disciplinaryOrgId">
          <div class="el-form-item__content">
            <el-select v-model="supervisoryParentId" @change='onSupervisoryParentIdChanged' placeholder="先选择一级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in orgList1" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="filing.supervisoryOrgId" placeholder="再选择二级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in supervisoryOrgList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="立案时间" prop="filingTime">
          <el-date-picker v-model="filing.filingTime" type="date" placeholder="立案时间" />
        </el-form-item>
        <el-form-item label="移送审理时间" prop="transferTime">
          <el-date-picker v-model="filing.transferTime" type="date" placeholder="处置时间" />
        </el-form-item>
        <el-form-item label="审理机关" prop="trialOrgId" style="display: flow">
          <div class="el-form-item__content">
            <el-select v-model="trialParentId" @change='onTrialParentIdChanged' placeholder="先选择一级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in orgList1" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="filing.trialOrgId" placeholder="再选择二级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in trialOrgList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="审结时间" prop="concludeTime">
          <el-date-picker v-model="filing.concludeTime" type="date" placeholder="办结时间" />
        </el-form-item>
        <el-form-item label="结案时间" prop="closureTime">
          <el-date-picker v-model="filing.closureTime" type="date" placeholder="办结时间" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="tryCreateFiling">确定</el-button>
        <el-button v-else type="primary" @click="tryUpdateFiling">确定</el-button>
      </div>
    </el-dialog>

    <!--导入对话框-->
    <el-dialog title="导入立案信息" :visible.sync="showImportFilingDialog" width="40%">
      <el-form ref="importFilingForm" :model="filingFile" label-position="left" label-width="100px" style="width: 600px; margin-left:50px;">
        <el-form-item label="上传文件" prop="title">
          <el-upload ref="upload" :action="importFilingUrl" :auto-upload="false" :limit="1" accept=".xls;.xlsx" :on-exceed="exceedFileListSize">
            <el-button slot="trigger" size="small" type="primary">选取Excel文件</el-button>
            <div class="el-upload__tip">xlsx文件, 1M以内，格式见模板下载</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showImportFilingDialog = false">取消</el-button>
        <el-button type="primary" @click="tryImportFilingFile">确定</el-button>
      </div>
    </el-dialog>

    <!--导入结果对话框-->
    <el-dialog title="导入结果" :visible.sync="showImportResultDialog">
      <el-table :data="importResult.data" border fit highlight-current-row>
        <el-table-column label="立案编码" width="300" align="left">
          <template slot-scope="scope">
            {{ (scope.row.value||{}).serial }}
          </template>
        </el-table-column>
        <el-table-column label="结果" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.result | resultClassFilter">{{ scope.row.result }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left">
          <template slot-scope="scope">
            {{ scope.row.message }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCloseImportResultEvent">关闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="流程图" :visible.sync="showWorkflowDialog" width="900px">
      <FilingWorkflow :clue="workflow.clue" :filing="workflow.filing"> </FilingWorkflow>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleCloseWorkflowDialogEvent">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import store from '@/store'
import { MessageBox } from 'element-ui'
import { createFiling, updateFiling, deleteFiling, getFilingList } from '@/api/filing'
import { getClueList } from '@/api/clue'
import { getOrgList } from '@/api/org'
import { getDateString } from '@/utils'
import { getToken } from '@/utils/auth'
import { parseErrorMessage } from '@/utils/request'
import FilingWorkflow from './components/FilingWorkflow'

export default {
  components: { FilingWorkflow },
  filters: {
    statusClassFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'warning',
        2: 'warning',
        3: 'success'
      }
      return statusMap[status]
    },
    statusValueFilter(status) {
      const statusMap = {
        0: '未处理',
        1: '已移交',
        2: '已审结',
        3: '已结案'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      total: null,
      listQuery: {
        page: 1,
        size: 20,
        f_lk_serial: undefined,
        f_lk_involvedPerson: undefined,
        f_eq_parentOrgId: '',
        f_eq_orgId: '',
        f_eq_status: undefined
      },
      orgList1: [],
      orgList2: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '增加',
        update: '修改'
      },
      rules: {
        serial: [{ required: true, message: '立案编码不能为空。', trigger: 'change' }],
        involvedPerson: [{ required: true, message: '涉案人员编码不能为空。', trigger: 'change' }],
        disciplinaryOrgId: [{ required: true, message: '纪委立案机关不能为空。', trigger: 'change' }],
        supervisoryOrgId: [{ required: true, message: '监委立案机关不能为空。', trigger: 'change' }],
        filingTime: [{ required: true, message: '立案时间不能为空。', trigger: 'change' }]
      },
      filing: {
        id: undefined,
        clueId: 0,
        respondent: undefined,
        serial: undefined,
        involvedPerson: undefined,
        filingTime: undefined,
        disciplinaryOrgId: 0,
        supervisoryOrgId: 0,
        transferTime: undefined,
        trialOrgId: 0,
        concludeTime: undefined,
        closureTime: undefined
      },
      clueList: [],
      disciplinaryParentId: 0,
      disciplinaryOrgList: [],
      supervisoryParentId: 0,
      supervisoryOrgList: [],
      trialParentId: 0,
      trialOrgList: [],
      showImportFilingDialog: false,
      importFilingUrl: process.env.VUE_APP_BASE_API + '/api/flow/filings/import',
      filingFile: {},
      showImportResultDialog: false,
      importResult: {},
      showWorkflowDialog: false,
      workflow: {
        clue: {},
        filing: {}
      }
    }
  },
  created() {
    // 查询数据
    this.fetchData()
    // 查询一级部门
    this.fetchOrgList1()
  },
  methods: {
    fetchOrgList1() {
      getOrgList({ f_eq_type: 1 }).then(response => {
        this.orgList1 = response.data
      })
    },
    fetchOrgList2(parentId) {
      getOrgList({ f_eq_parentId: parentId }).then(response => {
        this.orgList2 = response.data
      })
    },
    onOrgList1Changed() {
      if (this.listQuery.f_eq_parentOrgId !== '') {
        this.fetchOrgList2(this.listQuery.f_eq_parentOrgId)
      } else {
        this.orgList2 = []
      }
      // 一级部门改变后，默认二级部门默认全选
      this.listQuery.f_eq_orgId = ''
      this.listQuery.page = 1
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getFilingList(this.listQuery).then(response => {
        this.listLoading = false
        this.list = response.data
        this.total = response.total
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetFiler() {
      this.listQuery.f_lk_serial = undefined
      this.listQuery.f_lk_involvedPerson = undefined
      this.listQuery.f_eq_parentOrgId = ''
      this.listQuery.f_eq_orgId = ''
      this.listQuery.page = 1
      this.listQuery.size = 20
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    fetchClueList() {
      // 只查询办理结果为立案的线索
      getClueList({ f_eq_conclusion: 1 }).then(response => {
        this.clueList = response.data
      })
    },
    onDisciplinaryParentIdChanged() {
      getOrgList({ f_eq_parentId: this.disciplinaryParentId }).then(response => {
        this.disciplinaryOrgList = response.data
        if (this.disciplinaryOrgList && this.disciplinaryOrgList.length > 0) {
          this.filing.disciplinaryOrgId = this.disciplinaryOrgList[0].id
        }
      })
    },
    onSupervisoryParentIdChanged() {
      getOrgList({ f_eq_parentId: this.supervisoryParentId }).then(response => {
        this.supervisoryOrgList = response.data
        if (this.supervisoryOrgList && this.supervisoryOrgList.length > 0) {
          this.filing.supervisoryOrgId = this.supervisoryOrgList[0].id
        }
      })
    },
    onTrialParentIdChanged() {
      getOrgList({ f_eq_parentId: this.trialParentId }).then(response => {
        this.trialOrgList = response.data
        if (this.trialOrgList && this.trialOrgList.length > 0) {
          this.filing.trialOrgId = this.trialOrgList[0].id
        }
      })
    },
    handleCreateFilingEvent() {
      this.filing.id = 0
      this.filing.clueId = 0
      this.filing.filingTime = getDateString()
      this.filing.disciplinaryOrgId = 0
      this.filing.supervisoryOrgId = 0
      this.filing.trialOrgId = 0

      this.disciplinaryParentId = 0
      this.supervisoryParentId = 0
      this.trialParentId = 0

      // 查询线索列表
      this.fetchClueList()

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryCreateFiling() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createFiling(this.filing).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleUpdateFilingEvent(row) {
      const t = Object.assign({}, row) // copy obj
      this.filing.id = t.id
      this.filing.clueId = t.clueId
      this.filing.respondent = t.respondent
      this.filing.serial = t.serial
      this.filing.involvedPerson = t.involvedPerson
      this.filing.filingTime = t.filingTime
      this.filing.disciplinaryOrgId = t.disciplinaryOrgId
      this.filing.supervisoryOrgId = t.supervisoryOrgId
      this.filing.transferTime = t.transferTime
      this.filing.trialOrgId = t.trialOrgId
      this.filing.concludeTime = t.concludeTime
      this.filing.closureTime = t.closureTime

      this.disciplinaryParentId = (t.disciplinaryOrg || {}).parentId || 0
      this.supervisoryParentId = (t.supervisoryOrg || {}).parentId || 0
      this.trialParentId = (t.trialOrg || {}).parentId || 0

      // 查询线索列表
      this.fetchClueList()

      // 根据一级部门，更新二级部门列表
      getOrgList({ f_eq_parentId: this.disciplinaryParentId }).then(response => {
        this.disciplinaryOrgList = response.data
      })

      getOrgList({ f_eq_parentId: this.supervisoryParentId }).then(response => {
        this.supervisoryOrgList = response.data
      })

      getOrgList({ f_eq_parentId: this.trialParentId }).then(response => {
        this.trialOrgList = response.data
      })

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryUpdateFiling() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const filing = Object.assign({}, this.filing)
          updateFiling(filing).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleDeleteFilingEvent(id) {
      MessageBox.confirm('请确认是否要删除该记录？', '操作确认', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' })
        .then(() => {
          deleteFiling(id).then(() => {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }, () => {
        })
    },
    handleImportFilingEvent() {
      this.showImportFilingDialog = true
      this.$nextTick(() => {
        this.$refs['importFilingForm'].clearValidate()
      })
    },
    exceedFileListSize(files, fileList) {
      fileList.pop()
      fileList.push(files[0])
    },
    tryImportFilingFile() {
      // 此处仍使用validate机制，是为了以后对其他字段进行输入校验
      this.$refs['importFilingForm'].validate((valid) => {
        if (valid) {
          if (this.$refs.upload.uploadFiles.length === 0) {
            this.$message.error('请选择Excel(*xls;*.xlsx)文件')
            return
          }

          const files = this.$refs.upload.uploadFiles
          for (const file of files) {
            const name = file.name.toLowerCase()
            if (!name.endsWith('.xls') && !name.endsWith('.xlsx')) {
              this.$message.error('文件格式错误，请上传xlxs文件')
              return
            }

            // 文件大小不超过10M
            if (file.size > 10485760) {
              this.$message.error('文件太大，请上传10M以内的文件')
              return
            }
          }

          // 自动从form中获取提交的字段（包括上传文件）
          const form = new FormData(this.$refs.importFilingForm.$el) // 文件对象

          // XMLHttpRequest 对象
          const xhr = new XMLHttpRequest()
          xhr.open('post', this.importFilingUrl, true)

          // 加入Token做鉴权，此处使用XMLHttpRequest方式，就是为了在header中能够携带token
          xhr.setRequestHeader('Authorization', getToken())

          const $this = this
          xhr.onload = function() {
            if (xhr.status === 401) {
              store.dispatch('FedLogOut').then(() => {
                location.reload()// 为了重新实例化vue-router对象 避免bug
              })
            } else if (xhr.status < 200 || xhr.status >= 300) {
              const error = parseErrorMessage(xhr.responseText)
              $this.$message.error(error || '上传文件失败')
            } else {
              $this.$refs.upload.clearFiles()
              $this.showImportFilingDialog = false
              $this.showImportResultDialog = true
              $this.importResult = JSON.parse(xhr.responseText)
            }
          }

          xhr.onerror = function(xhr, e) {
            $this.$message.error('上传文件失败')
          }

          // 发送请求
          xhr.send(form)
        }
      })
    },
    handleCloseImportResultEvent() {
      this.showImportResultDialog = false
      this.fetchData()
    },
    handleExportExcelEvent(id) {
      axios.get(process.env.VUE_APP_BASE_API + '/api/flow/filings/' + id + '/export', { responseType: 'blob', headers: { Authorization: getToken() }})
        .then(({ data }) => {
          // console.log(data)
          const blob = new Blob([data], { type: 'application/octet-stream' })
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', '审查调查全周期管控表.xlsx')
          link.click()
        }).catch(error => {
          if (error.response.status === 401) {
            store.dispatch('FedLogOut').then(() => {
              location.reload()// 为了重新实例化vue-router对象 避免bug
            })
          }
        })
    },
    handleShowWorkflowDialogEvent(row) {
      this.workflow.clue = row.clue || {}
      this.workflow.filing = row
      this.showWorkflowDialog = true
    },
    handleCloseWorkflowDialogEvent() {
      this.showWorkflowDialog = false
    },
    downloadTemplate() {
      axios.get(process.env.VUE_APP_BASE_API + '/api/flow/filings/import/template', { responseType: 'blob', headers: { Authorization: getToken() }})
        .then(({ data }) => {
          // console.log(data)
          const blob = new Blob([data], { type: 'application/octet-stream' })
          const link = document.createElement('a')
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', '立案信息导入模板.xls')
          link.click()
        }).catch(error => {
        if (error.response.status === 401) {
          store.dispatch('FedLogOut').then(() => {
            location.reload()// 为了重新实例化vue-router对象 避免bug
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .query-label {
    display: inline-block;
    vertical-align: middle;
    margin: 0 0 10px 20px ;
    font-size: 14px;
    color: #909399;
  }
  // 将两个选择框水平显示
  .el-form-item__content {
    width: 500px;
    display: flow;
  }
</style>
